<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :class-name="'sub-navbar draft'">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">发布
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>

          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.title" :maxlength="100" name="name" required>
                标题
              </MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="45px" label="分类:" class="postInfo-container-item">
                    <el-select v-model="postForm.category_id" :remote-method="getCategoryList" filterable remote placeholder="分类">
                      <el-option v-for="(item,index) in categoryListOptions" :key="item.name+index" :label="item.name" :value="item.id"/>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="45px" label="摘要:">
          <el-input :rows="1" v-model="postForm.content_short" type="textarea" class="article-textarea" autosize placeholder="请输入内容"/>
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}字</span>
        </el-form-item>

        <div class="upload-container">
          <el-upload
            :headers="myHeaders"
            :multiple="false"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            class="image-uploader"
            drag
            action="/api/backstage/upload">
            <i class="el-icon-upload"/>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <div class="image-preview image-app-preview">
            <div v-if="imageUrl" class="image-preview-wrapper">
              <img :src="imageUrl" class="new-upload">
              <div class="image-preview-action">
                <i class="el-icon-delete" @click="rmImage"/>
              </div>
            </div>
          </div>
        </div>

        <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" :height="400" v-model="postForm.content" />
        </el-form-item>

      </div>
    </el-form>

  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { create, firstId, update } from '@/api/backstage/baike/article'
import { list } from '@/api/backstage/baike/category'
import { getToken } from '@/utils/auth'

const defaultForm = {
  category_id: '',
  status: true,
  title: '', // 文章题目
  content: '', // 文章内容
  content_short: '', // 文章摘要
  media_id: '', // 文章图片
  id: undefined
}

export default {
  name: 'ArticleDetail',
  components: { Tinymce, MDinput, Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      const errorFile = {
        title: '标题',
        content: '文章内容',
        content_short: '文章摘要',
        media_id: '文章图片'
      }
      if (value === '') {
        this.$message({
          message: errorFile[rule.field] + '为必传项',
          type: 'error'
        })
        callback(new Error(errorFile[rule.field] + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      imageUrl: '',
      myHeaders: { Authorization: 'Bearer ' + getToken() },
      postForm: Object.assign({}, defaultForm),
      loading: false,
      categoryListOptions: [],
      rules: {
        media_id: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }]
      },
      tempRoute: {}
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.content_short.length
    },
    lang() {
      return this.$store.getters.language
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    rmImage() {
      this.imageUrl = ''
      this.postForm.media_id = ''
    },
    emitInput(val) {
      this.postForm.media_id = val
    },
    handleImageSuccess(file) {
      this.imageUrl = file.data.path
      this.emitInput(file.data.id)
    },
    beforeUpload() {
    },
    fetchData(id) {
      firstId(id).then(response => {
        this.postForm = response.data
        // Just for test
        this.postForm.content_short = response.data.guide
        this.postForm.content = response.data.content.data ? response.data.content.data.content : ''
        this.imageUrl = response.data.media.data.path
        var name = response.data.category.data ? response.data.category.data.name : ''
        this.getCategoryList(name)
        // Set tagsview title
        this.setTagsViewTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    setTagsViewTitle() {
      const title = this.lang === 'zh' ? '编辑文章' : 'Edit Article'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.title}` })
      this.$store.dispatch('updateVisitedView', route)
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          const data = {
            category_id: this.postForm.category_id,
            status: this.postForm.status,
            title: this.postForm.title, // 文章题目
            content: this.postForm.content, // 文章内容
            guide: this.postForm.content_short, // 文章摘要
            media_id: this.postForm.media_id // 文章图片
          }
          if (this.postForm.id !== undefined) {
            const id = this.postForm.id
            update(data, id).then(() => {
              this.loading = true
              this.$notify({
                title: '成功',
                message: '发布文章成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.push('/baike/article')
            })
          } else {
            create(data).then(() => {
              this.loading = true
              this.$notify({
                title: '成功',
                message: '发布文章成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.push('/baike/article')
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getCategoryList(query) {
      const data = {
        name: query
      }
      list(data).then(response => {
        if (!response.data) return
        this.categoryListOptions = response.data
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/styles/mixin.scss";
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: -10px;
    top: 0px;
  }
}
.upload-container {
  width: 100%;
  position: relative;
  @include clearfix;
  .image-uploader {
    width: 35%;
    float: left;
  }
  .image-preview {
    width: 200px;
    height: 200px;
    position: relative;
    border: 1px dashed #d9d9d9;
    float: left;
    margin-left: 50px;
    .image-preview-wrapper {
      position: relative;
      width: 100%;
      height: 100%;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .image-preview-action {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      cursor: default;
      text-align: center;
      color: #fff;
      opacity: 0;
      font-size: 20px;
      background-color: rgba(0, 0, 0, .5);
      transition: opacity .3s;
      cursor: pointer;
      text-align: center;
      line-height: 200px;
      .el-icon-delete {
        font-size: 36px;
      }
    }
    &:hover {
      .image-preview-action {
        opacity: 1;
      }
    }
  }
  .image-app-preview {
    width: 320px;
    height: 180px;
    position: relative;
    border: 1px dashed #d9d9d9;
    float: left;
    margin-left: 50px;
    .app-fake-conver {
      height: 44px;
      position: absolute;
      width: 100%; // background: rgba(0, 0, 0, .1);
      text-align: center;
      line-height: 64px;
      color: #fff;
    }
  }
}
</style>
